/*
 * @Description:
 * @Version: 1.0
 * @Autor: wangmeng
 * @Date: 2021-08-03 11:13:38
 * @LastEditors: wamgmeng
 * @LastEditTime: 2024-01-18 15:11:04
 */
/* eslint-disable no-param-reassign */
import axios from "axios";
import qs from "qs";
import { ElMessage } from "element-plus";

const http = axios.create({
  timeout: 3000000,
  transformRequest: [
    function (data) {
      // 如果是FormData，直接返回，不进行JSON序列化
      if (data instanceof FormData) {
        return data;
      }
      return JSON.stringify(data);
    },
  ],
});

// http request 拦截器
http.interceptors.request.use(
  (config) => {
    // 如果是FormData，不设置Content-Type，让浏览器自动处理
    if (config.data instanceof FormData) {
      // 不设置Content-Type，让浏览器自动设置multipart/form-data
    } else {
      config.headers = {
        "Content-Type": "application/json",
      } as any;
    }
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);

// http response 拦截器
http.interceptors.response.use(
  (response) => {
    if (response.status < 400) {
      if (response.data.code === 302 || response.data.status === 302) {
        ElMessage.error("登录已过期，请重新登录");
        window.location.href = "#/login";
      }
      if (response.config?.url?.includes("/apibackup/database")) {
        if (response.status === 200) {
          return Promise.resolve(true);
        } else {
          return Promise.reject(false);
        }
      } else {
        // 400003状态码：服务端拒绝访问，目前用于考试屏蔽中的教室获取流的接口
        if (
          response.data.code === 0 ||
          response.data.status === 0 ||
          response.data.status === 400003
        ) {
          if (response.data.status === 0) {
            return Promise.resolve(response.data.data);
          } else {
            return Promise.reject(response.data.message);
          }
        }
        return Promise.reject(response.data);
      }
    }
    return Promise.reject();
  },
  () => {
    return Promise.reject();
  }
);

const formDataHttp = axios.create({
  timeout: 3000000,
  transformRequest: [
    function (data) {
      return qs.stringify(data);
    },
  ],
});

// http request 拦截器
formDataHttp.interceptors.request.use(
  (config) => {
    config.headers = {
      "Content-Type": "application/x-www-form-urlencoded",
    } as any;
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);

// http response 拦截器
formDataHttp.interceptors.response.use(
  (response) => {
    if (response.status < 400) {
      if (response.data.code === 302 || response.data.status === 302) {
        const _result = response.data.result || response.data.message;
        const _root =
          _result.includes("http://") || _result.includes("https://")
            ? ""
            : "http://";
        setTimeout(() => {
          if (_result.includes("serverName")) {
            window.location.href = `${_root}${_result}`;
          } else {
            window.location.href = `${_root}${_result}?serverName=${encodeURIComponent(
              window.btoa(window.location.href)
            )}`;
          }
        }, 300);
      }
      // 400003状态码：服务端拒绝访问，目前用于考试屏蔽中的教室获取流的接口
      if (
        response.data.code === 0 ||
        response.data.status === 0 ||
        response.data.status === 400003
      ) {
        return Promise.resolve(response.data);
      }
      return Promise.reject(response.data);
    }
    return Promise.reject();
  },
  () => {
    return Promise.reject();
  }
);

export { http, formDataHttp };

// 专门用于文件上传的axios实例
const fileUploadHttp = axios.create({
  timeout: 3000000,
  transformRequest: [
    function (data) {
      // 对于FormData，直接返回，不进行任何转换
      if (data instanceof FormData) {
        return data;
      }
      // 对于非FormData数据，进行JSON序列化
      return JSON.stringify(data);
    },
  ],
});

// 文件上传请求拦截器
fileUploadHttp.interceptors.request.use(
  (config) => {
    // 对于FormData，不设置Content-Type，让浏览器自动设置为multipart/form-data
    if (config.data instanceof FormData) {
      // 删除可能存在的Content-Type，让浏览器自动处理
      if (config.headers) {
        delete config.headers["Content-Type"];
      }
    } else {
      // 对于非FormData数据，设置JSON Content-Type
      config.headers = {
        "Content-Type": "application/json",
      } as any;
    }
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);

// 文件上传响应拦截器
fileUploadHttp.interceptors.response.use(
  (response) => {
    if (response.status < 400) {
      if (response.data.code === 302 || response.data.status === 302) {
        ElMessage.error("登录已过期，请重新登录");
        window.location.href = "#/login";
      }
      // 400003状态码：服务端拒绝访问，目前用于考试屏蔽中的教室获取流的接口
      if (
        response.data.code === 0 ||
        response.data.status === 0 ||
        response.data.status === 400003
      ) {
        if (response.data.status === 0) {
          return Promise.resolve(response.data.data);
        } else {
          return Promise.reject(response.data.message);
        }
      }
      return Promise.reject(response.data);
    }
    return Promise.reject();
  },
  () => {
    return Promise.reject();
  }
);

export { fileUploadHttp };
